home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16079 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c,comp.lang.c++
  4. Subject: Re: returning an array from function
  5. Date: Tue, 09 Apr 96 11:17:58 GMT
  6. Organization: none
  7. Message-ID: <829048678snz@genesis.demon.co.uk>
  8. References: <4jstd8$kh0@news1.sunbelt.net> <Pine.A32.3.91.960407035313.115982E-100000@magritte.its.rpi.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <Pine.A32.3.91.960407035313.115982E-100000@magritte.its.rpi.edu>
  15.            hashik@rpi.edu "Kengo Hashimoto" writes:
  16.  
  17. >Just do a call-by-reference to the array, or return a pointer to the 
  18. >first member of the array. Here are examples:
  19. >
  20. >call-by-reference:
  21. >
  22. >void foo(int &[]);    // just pass the array in there, manipulate it 
  23. >                      // within foo(), and the original copy would be 
  24. >                      // modified as well.
  25.  
  26. Note the code above is only meaningful in C++ (this was cross-posted to
  27. comp.lang.c). In C you can achieve a similar effect by passing a pointer.
  28.  
  29. >returning a pointer:
  30. >int *foo();
  31. >
  32. >int bar[arraysize];
  33. >
  34. >bar = foo();
  35.  
  36. You can't assign to an array.
  37.  
  38. >foo() {
  39.  
  40. int *foo() {
  41.  
  42. >  foo2[arraysize];
  43.  
  44.    int foo2[arraysize];
  45.  
  46. >  return &(foo2[0]);
  47. >}
  48.  
  49. foo2 is a local variable which is destroyed when the function returns so
  50. a pointer to it is indeterminate and can't be used in the caller. 
  51.  
  52. >Those two approaches should work. Remember, the name of an array without 
  53. >the [] is simply a pointer to the array.
  54.  
  55. In a value context (there are a number of contexts where an array name
  56. can appear but not be used as a value) an array name (or other array lvalue)
  57. evaluates to a pointer to the first element of the array. This is not the
  58. same thing as a pointer to the array.
  59.  
  60. -- 
  61. -----------------------------------------
  62. Lawrence Kirby | fred@genesis.demon.co.uk
  63. Wilts, England | 70734.126@compuserve.com
  64. -----------------------------------------
  65.